package com.wyzz.hr.action;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.*;
import org.apache.commons.lang.StringUtils;

import com.wyzz.hr.base.BaseDownloadAction;
import com.wyzz.hr.base.FileOperate;
import com.wyzz.hr.base.Status;
import com.wyzz.hr.bo.IAttendshiftBO;
import com.wyzz.hr.bo.IDepartmentBO;
import com.wyzz.hr.bo.IEmployeeBo;
import com.wyzz.hr.bo.ILeavebalanceBO;
import com.wyzz.hr.bo.ILeaverequestBO;
import com.wyzz.hr.bo.ILeavetypeBO;
import com.wyzz.hr.bo.impl.ExaminDateUtil;
import com.wyzz.hr.bo.impl.LrDataCheckImpl;
import com.wyzz.hr.exportfile.ExportLeavebalance;
import com.wyzz.hr.pojo.Attendshift;
import com.wyzz.hr.pojo.Employee;
import com.wyzz.hr.pojo.Leavebalance;
import com.wyzz.hr.pojo.Leavetype;
import com.wyzz.hr.spring.SpringBeanFactory;
import com.wyzz.hr.util.DateUtil;
import com.wyzz.hr.util.MyTools;
import com.wyzz.hr.util.Pager;
import com.wyzz.hr.util.impl.PropertiesFileConfigManager;

public class LeavebalanceCurrentYear extends BaseDownloadAction {

	public LeavebalanceCurrentYear() {
		page = new Pager();
		searchType = "1";
	}

	public String execute() throws Exception {
		if (leaveBalance == null) {
			leaveBalance = new Leavebalance();
			leaveBalance.setLbYear(String
					.valueOf(Calendar.getInstance().get(1)));
			leaveBalance.setLbLeaveType(Integer.valueOf(1));
			leaveBalance.setLbStatus(Integer.valueOf(0));
			leaveType = "0";
		}
		if (StringUtils.isEmpty(leaveBalance.getLbYear())
				|| leaveBalance.getLbYear().equals("NaN"))
			leaveBalance.setLbYear(String
					.valueOf(Calendar.getInstance().get(1)));
		locationList = getDrillDown("Location", new String[] { "1" });
		IEmployeeBo empBo = (IEmployeeBo) getBean("empBo");
		empList = empBo.findAllActiveEmployees(leaveBalance.getLbYear());
		ILeavebalanceBO lb_BO = (ILeavebalanceBO) getBean("leavebalanceBO");
		if ("export".equals(searchOrExport)) {
			if (searchType.equals("1")) {
				result = lb_BO.getEmpWithLB(leaveBalance, null);
			} else {
				leaveBalance.setLbStatus(Integer.valueOf(1));
				result = lb_BO.getEmpWithoutLB(leaveBalance, null);
			}
			if (result == null || result.isEmpty()) {
				addActionError("\u65E0\u5458\u5DE5\u4F11\u5047\u7BA1\u7406\u6570\u636E\u53EF\u4EE5\u5BFC\u51FA\uFF01");
				return "success";
			}
			int lbLeaveType = ((Employee) result.get(0)).getLeaveBalance()
					.getLbLeaveType().intValue();
			ILeavetypeBO ltBO = (ILeavetypeBO) getBean("leavetypeBO");
			Leavetype lt = ltBO.getLeavetypeByCat(Integer.valueOf(lbLeaveType));
			LrDataCheckImpl lrAddCheckData = (LrDataCheckImpl) getBean("lrDataCheck");
			double leaveDate[] = { 0.0D, 0.0D };
			double hoursPerDay = ExaminDateUtil.getDefaultHoursPerDay();
			Employee emp;
			for (Iterator i$ = result.iterator(); i$.hasNext(); emp
					.getLeaveBalance().setCanUseTotalDays(
							MyTools.round(leaveDate[1] / hoursPerDay, 2))) {
				emp = (Employee) i$.next();
				if (lbLeaveType == 1)
					leaveDate = lrAddCheckData.getAnnualLeaveDate(emp, lt, emp
							.getLeaveBalance());
				else
					leaveDate = lrAddCheckData.getSick02LeaveDate(emp, lt, emp
							.getLeaveBalance());
				emp.getLeaveBalance().setUsedTotalDays(
						MyTools.round(leaveDate[0] / hoursPerDay, 2));
			}

			IDepartmentBO deptBo = (IDepartmentBO) SpringBeanFactory
					.getBean("departmentBO");
			deptBo.setListDeptLevels(result, "empDeptNo", "empBranch",
					"empDeptNo", new String[0]);
			return exportData(result);
		}
		if (searchType.equals("1")) {
			result = lb_BO.getEmpWithLB(leaveBalance, page);
		} else {
			leaveBalance.setLbStatus(Integer.valueOf(1));
			result = lb_BO.getEmpWithoutLB(leaveBalance, page);
		}
		return "success";
	}

	private String exportData(List result) {
		String downFileName = null;
		String filePath = FileOperate.getFileHomePath();
		String xslFileName = (new StringBuilder()).append("export-").append(
				FileOperate.buildFileName()).append(
				PropertiesFileConfigManager.getInstance().getProperty(
						"sys.saveDir.type").trim()).toString();
		filePath = (new StringBuilder()).append(filePath).append(xslFileName)
				.toString();
		try {
			ExportLeavebalance exportLb = new ExportLeavebalance(result,
					"\u5BFC\u51FA");
			exportLb.export(filePath);
			if (leaveBalance.getLbLeaveType().intValue() == 1)
				downFileName = "AnnualLeaveBalance.xls";
			else
				downFileName = "Sick02LeaveBalance.xls";
			File file = new File(filePath);
			FileInputStream fileInputStream = new FileInputStream(file);
			setDocStream(fileInputStream);
			setContentDisposition((new StringBuilder()).append("filename=\"")
					.append(downFileName).append("\"").toString());
			setServerFileName(filePath);
			clearErrorsAndMessages();
		} catch (Exception e) {
			addActionError("\u6570\u636E\u5BFC\u51FA\u5931\u8D25\uFF01");
			e.printStackTrace();
			return "success";
		}
		return "download";
	}

	public String initLeaveBalance() {
		if (StringUtils.isEmpty(updateIDs)) {
			addActionError("\u8BF7\u9009\u62E9\u8981\u8FDB\u884C\u521D\u59CB\u5316\u7684\u5458\u5DE5\u8BB0\u5F55\uFF01");
			return "success";
		}
		if (StringUtils.isEmpty(specialIds)) {
			addActionError("\u8BF7\u9009\u62E9\u8981\u521D\u59CB\u5316\u7684\u5047\u671F\u79CD\u7C7B\uFF01");
			return "success";
		}
		if (leaveBalance == null
				|| StringUtils.isEmpty(leaveBalance.getLbYear())) {
			addActionError("\u8BF7\u9009\u62E9\u8981\u8FDB\u884C\u521D\u59CB\u5316\u7684\u5E74\u4EFD\uFF01");
			return "success";
		}
		ILeavebalanceBO lb_BO = (ILeavebalanceBO) getBean("leavebalanceBO");
		String empIds[] = updateIDs.split(";");
		Integer ltSpecialCat[] = converToIntegerArray(specialIds);
		String year = leaveBalance.getLbYear();
		List result = lb_BO.exeLeaveBalanceInit(empIds, ltSpecialCat, year);
		if (!result.isEmpty()) {
			addErrorInfo(result);
			return "success";
		} else {
			addSuccessInfo((new StringBuilder())
					.append(year)
					.append(
							"\u5E74\u7684\u5047\u671F\u521D\u59CB\u5316\u6210\u529F\uFF01")
					.toString());
			return "success";
		}
	}

	private Integer[] converToIntegerArray(String str) {
		String strArr[] = str.split(",");
		Integer intArr[] = new Integer[strArr.length];
		for (int i = 0; i < strArr.length; i++)
			intArr[i] = Integer.valueOf(strArr[i]);

		return intArr;
	}

	public String doSubmitLeaveBalance() {
		if (StringUtils.isEmpty(updateIDs)) {
			addActionError("\u8BF7\u9009\u62E9\u8981\u8FDB\u884C\u63D0\u4EA4\u7684\u4F11\u5047\u8BB0\u5F55!");
			return "success";
		}
		String recordIds[] = updateIDs.split(",");
		ILeavebalanceBO leaveBalanceBo = (ILeavebalanceBO) getBean("leavebalanceBO");
		List result = leaveBalanceBo.exeSubmitLeaveBalance(recordIds);
		if (!result.isEmpty()) {
			addErrorInfo(result);
			return "success";
		} else {
			addSuccessInfo("\u64CD\u4F5C\u6210\u529F!");
			return "success";
		}
	}

	public String doDeleteLeaveBalance() {
		if (StringUtils.isEmpty(updateIDs)) {
			addActionError("\u8BF7\u9009\u62E9\u8981\u8FDB\u884C\u5BA1\u6838\u7684\u4F11\u5047\u8BB0\u5F55!");
			return "success";
		}
		ILeavebalanceBO leaveBalanceBo = (ILeavebalanceBO) getBean("leavebalanceBO");
		String recordIds[] = updateIDs.split(",");
		List result = leaveBalanceBo.exeDeleteLeaveBalance(recordIds);
		if (!result.isEmpty()) {
			addErrorInfo(result);
			return "success";
		} else {
			addSuccessInfo("\u64CD\u4F5C\u6210\u529F!");
			return "success";
		}
	}

	public List getEmpLtInfo(String year, String empId, int ltSpecialCat,
			int dayOrHour) {
		LrDataCheckImpl lrAddCheckData = (LrDataCheckImpl) getBean("lrDataCheck");
		IEmployeeBo empBo = (IEmployeeBo) getBean("empBo");
		IAttendshiftBO attendBo = (IAttendshiftBO) getBean("attendshiftBO");
		ILeavetypeBO lt_BO = (ILeavetypeBO) getBean("leavetypeBO");
		ILeaverequestBO lr_BO = (ILeaverequestBO) getBean("leaverequestBO");
		ILeavebalanceBO lbBO = (ILeavebalanceBO) getBean("leavebalanceBO");
		int currentYear = Integer.parseInt(year);
		Date yearBeginDate = DateUtil.getYearFirstDay(currentYear);
		Date nextYearBeginDate = DateUtil
				.getNextYearFirstDay(currentYear);
		Employee currEmp = empBo.loadEmp(empId, null);
		Leavetype lt = lt_BO.getLeavetypeByCat(Integer.valueOf(ltSpecialCat));
		Attendshift defaultAs = attendBo.getDefaultAttendshiftByEmp(currEmp);
		double hoursPerDay;
		if (currEmp.getEmpShiftType().intValue() == 0
				|| currEmp.getEmpShiftType().intValue() == 2)
			hoursPerDay = defaultAs.getAttsWorkingHour().doubleValue();
		else
			hoursPerDay = ExaminDateUtil.getDefaultHoursPerDay();
		List dataList = lr_BO.getTotalStatusSetList(currEmp, yearBeginDate,
				nextYearBeginDate, lt, Status.PROCESSED);
		BigDecimal values[] = new BigDecimal[4];
		double calcValues[] = new double[2];
		Leavebalance lb = lbBO.getLeavebalance(new Employee(empId), year, lt);
		if (ltSpecialCat == 1)
			calcValues = lrAddCheckData.getAnnualLeaveDate(currEmp, lt, lb);
		else if (ltSpecialCat == 5)
			calcValues = lrAddCheckData.getSick02LeaveDate(currEmp, lt, lb);
		values[0] = new BigDecimal(calcValues[0]);
		values[1] = new BigDecimal(calcValues[1]);
		if (dayOrHour == 0) {
			values[0] = values[0].divide(new BigDecimal(hoursPerDay), 2, 4);
			values[1] = values[1].divide(new BigDecimal(hoursPerDay), 2, 4);
		}
		dataList.add(values);
		return dataList;
	}

	public Pager getPage() {
		return page;
	}

	public void setPage(Pager page) {
		this.page = page;
	}

	public List getLocationList() {
		return locationList;
	}

	public void setLocationList(List locationList) {
		this.locationList = locationList;
	}

	public List getResult() {
		return result;
	}

	public void setResult(List result) {
		this.result = result;
	}

	public Leavebalance getLeaveBalance() {
		return leaveBalance;
	}

	public void setLeaveBalance(Leavebalance leaveBalance) {
		this.leaveBalance = leaveBalance;
	}

	public String getUpdateIDs() {
		return updateIDs;
	}

	public void setUpdateIDs(String updateIDs) {
		this.updateIDs = updateIDs;
	}

	public String getSpecialIds() {
		return specialIds;
	}

	public void setSpecialIds(String specialIds) {
		this.specialIds = specialIds;
	}

	public List getEmpList() {
		return empList;
	}

	public void setEmpList(List empList) {
		this.empList = empList;
	}

	public String getSearchType() {
		return searchType;
	}

	public void setSearchType(String searchType) {
		this.searchType = searchType;
	}

	public String getLeaveType() {
		return leaveType;
	}

	public void setLeaveType(String leaveType) {
		this.leaveType = leaveType;
	}

	public String getSearchOrExport() {
		return searchOrExport;
	}

	public void setSearchOrExport(String searchOrExport) {
		this.searchOrExport = searchOrExport;
	}

	private static final long serialVersionUID = 1L;
	private Pager page;
	private List locationList;
	private List result;
	private List empList;
	private Leavebalance leaveBalance;
	private String updateIDs;
	private String specialIds;
	private String searchType;
	private String leaveType;
	private String searchOrExport;
}
